﻿using System;
using System.Text;
using Microsoft.Practices.ComponentModel;
using EnvDTE;
using System.Diagnostics;
using System.IO;
using Microsoft.Practices.RecipeFramework;
using EnvDTE80;
using VSSDKAssist.Assets.Actions.Base;
using VSSDKAssist.Assets.Helpers;

namespace VSSDKAssist.Assets.Actions.VisualStudio
{
	/// <summary>
	/// The action adds a file to the project item or solution item
	/// The other input properties of the action are 
	/// (a) SourceFileName - provides the name of the file 
	/// (b) SourceFilePath - provides the path name of the file
	/// </summary>
	[ServiceDependency(typeof(DTE))]
	public class AddItemFromFileToProjectItemAction : ActionBase
	{
		#region Properties

		private string sourceFileName;

		/// <summary>
		/// Name of the source file
		/// </summary>
		[Input(Required = true)]
		public string SourceFileName
		{
			get { return sourceFileName; }
			set { sourceFileName = value; }
		}

		private string sourceFilePath = string.Empty;

		/// <summary>
		/// Name of the source file path
		/// </summary>
		[Input(Required = false)]
		public string SourceFilePath
		{
			get { return sourceFilePath; }
			set { sourceFilePath = value; }
		}

		private ProjectItem inputProjectItem;

		/// <summary>
		/// The InputProjectItem object where add the file
		/// </summary>
		[Input(Required = true)]
		public ProjectItem InputProjectItem
		{
			get { return inputProjectItem; }
			set { inputProjectItem = value; }
		}

		private bool open = true;

		/// <summary>
		/// A flag to indicate if the newly created item should be shown
		/// in a window.
		/// </summary>
		[Input(Required = false)]
		public bool Open
		{
			get { return open; }
			set { open = value; }
		}

		private ProjectItem projectItem;

		/// <summary>
		/// A property that can be used to pass the creted item to
		/// a following action.
		/// </summary>
		[Output]
		public ProjectItem ProjectItem
		{
			get { return projectItem; }
			set { projectItem = value; }
		}
		#endregion

		/// <summary>
		/// Called when [execute].
		/// </summary>
		protected override void OnExecute()
		{
			string fileName = this.sourceFileName;

			if(!string.IsNullOrEmpty(this.sourceFilePath))
			{
				fileName = Path.Combine(this.sourceFilePath, this.sourceFileName);
			}

			projectItem = VSIPHelper.FindItemByName(this.InputProjectItem.ProjectItems, Path.GetFileName(fileName), false);

			if(projectItem == null)
			{
				projectItem = this.InputProjectItem.ProjectItems.AddFromFileCopy(fileName);
			}
		}

		/// <summary>
		/// Called when [undo].
		/// </summary>
		protected override void OnUndo()
		{
			if(projectItem != null)
			{
				projectItem.Delete();
			}
		}
	}
}